import styles from "./index.module.scss"
import loginBg from "@/assets/images/common/login_bg.png"
import {useEffect, useState} from "react";
import {loginUrl} from "@/api/pages/login";
import {useNavigate} from "react-router-dom";
import {setTokenUtil} from "@/utils/tokenUtil";
import {Button, Checkbox, Form, Input, QRCode, Segmented} from "antd";
import {setToken} from "@/store/modules/userSlice.ts";
import {showNotification} from "@/components/OpComponent/Message";
import {checkQrCodeStatus, generateQrCode, getCaptchaImageUrl} from "@/api/login.ts";
import {LockOutlined, UserOutlined} from "@ant-design/icons";
import SvgIcon from "@/commponent/SvgIcon";
import {useDispatch} from "react-redux";
import Cookies from "js-cookie"


export default function Login() {
    // 登录方式 form qrcode
    const [loginType, setLoginType] = useState("form")

    const changeLoginType = () => {
        setLoginType(loginType === "form" ? "qrcode" : "form")
    }

    /*两个登录都在这里*/
    return <div className={styles.loginPage}>
        <div className={styles.loginContent}>
            <div className={styles.left}>
                <img src={loginBg} alt={""}/>
            </div>
            <div className={styles.right}>
                <h2>初雪管理系统</h2>
                {loginType === "form" && <LoginForm/>}
                {loginType === "qrcode" && <QrCodeForm/>}
                {/*右下角扫码图标*/}
                <div className={styles.qrCode}>
                    <div onClick={changeLoginType}>
                        {loginType === "form" && <SvgIcon name={"CustomQrCode"} size={46}/>}
                        {loginType === "qrcode" && <SvgIcon name={"CustomPtLogin"} size={46}/>}
                    </div>
                    <div className={styles.shareBox}></div>
                </div>
            </div>
        </div>
    </div>
}

/**
 * 用户名密码登录
 * @constructor
 */
function LoginForm() {
    const navigate = useNavigate()
    const [loading, setLoading] = useState(false)
    const [captchaEnabled, setCaptchaEnabled] = useState(false)
    const [isRemember, setIsRemember] = useState(false)
    const [uuid, setUuid] = useState('')
    const [imgData, setImgData] = useState('')
    const dispatch = useDispatch()
    const [form] = Form.useForm();

    const getCode = () => {
        getCaptchaImageUrl().then(res => {
            const captchaEnabled = res.captchaEnabled
            setCaptchaEnabled(captchaEnabled)
            if (captchaEnabled) {
                setUuid(res.uuid)
                setImgData("data:image/gif;base64," + res.img)
            }
        })
    }

    const saveInCookies = (values: any) => {
        Cookies.set('isRemember', isRemember ? "true" : "false", { expires: 7 }); // 7天后过期
        if(isRemember){
            Cookies.set('username', values.username, { expires: 7 });
            Cookies.set('password', values.password, { expires: 7 });
        }else{
            Cookies.remove('username');
            Cookies.remove('password');
        }
    }

    const getInCookies = () => {
        console.log("getInCookies", Cookies.get('isRemember'))
        const isRemember = Cookies.get('isRemember') === 'true';
        setIsRemember(isRemember)
        if(isRemember){
            const username = Cookies.get('username');
            const password = Cookies.get('password');
            if (username && password) {
                form.setFieldsValue({
                    username: username,
                    password: password,
                });
            }
        }
    }

    const handleSubmit = (values: any) => {

        setLoading(true)
        // 这里可以调用 API 提交表单数据
        loginUrl({
            ...values,
            uuid: uuid,
        }).then(res => {
            setTokenUtil(res.token)
            saveInCookies(values)
            dispatch(setToken(res.token))
            navigate("/")
            // 弹出登录成功
            showNotification({
                content: "登录成功",
            })
        }).catch((err) => {
            getCode()
        }).finally(() => {
                setLoading(false)
            })
    };

    // 1. 初始化时读取缓存中信息，看是否有记住密码
    // 2. 提交表单时，判断是否记住密码，记住密码就保存到缓存中，不记住就删除缓存中的信息
    useEffect(() => {
        getCode()
        getInCookies()
    }, []);


    return <div className={styles.loginBox}>

       {/* <Segmented<string>
            style={{marginBottom: "26px"}}
            options={['用户名密码', '手机号', '电子邮箱']}
            onChange={(value) => {
                console.log(value); // string
            }}
        />*/}
        <Form layout={"vertical"}
              form={form}
              onFinish={handleSubmit}
              style={{marginTop: 32}}
        >
            <Form.Item required rules={[{required: true, message: '用户名不能为空!'}]} name={"username"}>
                <Input prefix={<UserOutlined/>} placeholder={"请输入用户名"}/>
            </Form.Item>
            <Form.Item required rules={[{required: true, message: '密码不能为空!'}]} name={"password"}>
                <Input.Password prefix={<LockOutlined/>} placeholder={"请输入密码"}/>
            </Form.Item>
            {captchaEnabled && <div className={styles.formItemCodeItem}>
                <Form.Item required className={styles.formItemCode}
                           rules={[{required: true, message: '验证码不能为空!'}]} name={"code"}>
                    <Input prefix={<SvgIcon name={"CustomVerificationCode"} size={15}/>} placeholder={"请输入验证码"}/>
                </Form.Item>
                <img
                    onClick={getCode}
                    className={styles.codeImg}
                    src={imgData}
                    alt={"验证码图片"}/>
            </div>
            }

            <Form.Item>
                {/* 忘记密码 + 是否记住密码 */}
                <div className={styles.forgetPwd}>
                    <Checkbox checked={isRemember} onChange={(e) => {
                        setIsRemember(e.target.checked)
                    }}>记住密码</Checkbox>
                    <a href={"#"}>忘记密码</a>
                </div>
                <Button type={"primary"} style={{width: "100%"}} loading={loading} htmlType={"submit"}
                        className={styles.loginBtn}>登录</Button>
            </Form.Item>
        </Form>
        {/*分割线*/}
        {/*<Divider>其他登录方式</Divider>*/}
        {/*<Space>*/}

        {/*</Space>*/}
    </div>
}


/**
 * 扫码验证登录
 * @constructor
 */
function QrCodeForm() {
    const [qrCodeId, setQrCodeId] = useState("");
    const [status, setStatus] = useState("");
    const [token, setToken] = useState("");
    const [errorMessage, setErrorMessage] = useState("");

    useEffect(() => {
        // 生成二维码
        generateQrCode().then(res => {
            setQrCodeId(res.data);
        }).catch(err => {
            setErrorMessage("生成二维码失败，请重试");
        });
    }, []);

    useEffect(() => {
        // 定期检查二维码状态
        let intervalId: NodeJS.Timeout;

        if (qrCodeId) {
            intervalId = setInterval(() => {
                checkQrCodeStatus(qrCodeId).then(res => {
                    const status = res.status;
                    if (status !== null) {
                        if (status === 0) {
                            setStatus("等待用户扫码");
                        } else if (status === 1) {
                            setStatus("用户已扫码，等待确认");
                        } else if (status === 2) {
                            setStatus("确认成功");
                            setToken(res.data.token);
                            clearInterval(intervalId); // 扫码成功后停止检查
                        } else {
                            setStatus("二维码已过期或无效");
                            clearInterval(intervalId); // 二维码无效后停止检查
                        }
                    } else {
                        setErrorMessage("检查二维码状态失败，请重试");
                        clearInterval(intervalId); // 检查失败后停止检查
                    }
                }).catch(err => {
                    setErrorMessage("检查二维码状态失败，请重试");
                    clearInterval(intervalId); // 检查失败后停止检查
                });
            }, 500); // 每5秒检查一次状态
        }

        return () => clearInterval(intervalId); // 清除定时器
    }, [qrCodeId]);

    return (
        <>
            {errorMessage && <div style={{color: 'red'}}>{errorMessage}</div>}
            {qrCodeId && <QRCode value={"http://192.168.31.182:3000/qrCodeLogin?qrCodeId=" + qrCodeId}/>}
            {status && <div>{status}</div>}
            {token && <div>登录成功，您的令牌是: {token}</div>}
        </>
    );
}
